package com.zhxy.manager.service.impl;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhxy.manager.dao.CleanDao;
import com.zhxy.manager.entity.Clean;
import com.zhxy.manager.excel.CleanExcel;
import com.zhxy.manager.service.intf.CleanService;
import com.zhxy.manager.vo.PageBean;
import com.zhxy.manager.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
public class CleanServiceImpl implements CleanService {
    @Autowired
    private CleanDao dao;

    @Override
    public R save(Clean clean) {
        if (dao.add(clean) > 0) {
            return R.ok();
        } else {
            return R.fail();
        }
    }

    @Override
    public List<Clean> queryAll() {
        return dao.selectAll();
    }

    @Override
    public R del(int id) {
        if (id > 0) {
            if (dao.del(id) > 0) {
                return R.ok();
            } else {
                return R.fail();
            }
        } else {
            return R.fail();
        }
    }

    @Override
    public R update(Clean clean) {
        if (dao.update(clean) > 0) {
            return R.ok();
        } else {
            return R.fail();
        }
    }

    @Override
    public PageBean queryPageWhere(String name, int sex, int page, int limit) {
        //1.验证 查询条件 如果为 "" 那么赋值为null
        if (!StringUtils.hasLength(name)) {
            name = null;
        } else {
            name = "%" + name + "%";//包含  模糊查询
        }
        PageHelper.startPage(page, limit);
        PageInfo<Clean> pageInfo = new PageInfo<>(dao.selectWhere(name,sex));
        return PageBean.bean(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    public R delBatch(int[] ids) {
        if (ids != null & ids.length > 0) {
            if (dao.delBatch(ids) > 0) {
                return R.ok();
            } else {
                return R.fail();
            }
        } else {
            return R.fail();
        }
    }

    @Override
    public R saveBatch(MultipartFile file) throws IOException {
       if (!file.isEmpty()){
           List<CleanExcel> list = EasyExcel.read(file.getInputStream(), CleanExcel.class, new ReadListener() {
               @Override
               public void invoke(Object o, AnalysisContext analysisContext) {}
               @Override
               public void doAfterAllAnalysed(AnalysisContext analysisContext) {}
           }).sheet().doReadSync();
           System.out.println(list);
        //执行dao 批量新增
        if(dao.addBatch(list)>0){
            return R.ok();
        }
    }
        return R.fail();
    }
}
